package com.caocaog.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.caocaog.market.entity.ShopPrinter;
import com.caocaog.market.mapper.ShopPrinterMapper;
import com.caocaog.market.service.ShopPrinterService;
import com.caocaog.market.utils.FePrinterUtil;
import com.caocaog.market.utils.XyyPrinterUtil;
import com.caocaog.market.utils.YlyPrinterUtil;
import com.caocaog.market.utils.ZwPrinterUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.CheckFailedException;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.vo.LoginUser;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 打印机设置
 *
 * @author chechen
 * @date 2021-12-01
 */
@Service
@Transactional
public class ShopPrinterServiceImpl extends ServiceImpl<ShopPrinterMapper, ShopPrinter> implements ShopPrinterService {

    @Override
    public IPage<ShopPrinter> queryShopPrinterPage(Page<ShopPrinter> page, ShopPrinter shopPrinter) {
        if (shopPrinter.getShopId() == null)
            throw new JeecgBootException("未找到相应门店下打印机设置, shopId-> " + shopPrinter.getShopId());
        IPage<ShopPrinter> shopPrinterIPage = super.baseMapper.queryShopPrinterPage(page, shopPrinter);
        // 依次获取打印机状态
        shopPrinterIPage.setRecords(shopPrinterIPage.getRecords().stream().peek(item -> {
            Result<String> statusResult = null;
            if (item.getType() == 1) { // 飞鹅
                statusResult = FePrinterUtil.getStatus(item.getNumber());
                // 易联云
            } else if (item.getType() == 2) {
                statusResult = YlyPrinterUtil.getStatus(item.getNumber());
                // 芯烨云
            } else if (item.getType() == 3) {
                statusResult = XyyPrinterUtil.getStatus(item.getNumber());
            } else if (item.getType() == 4) {
                statusResult = ZwPrinterUtil.getStatus(item.getNumber(), item.getPrinterKey());
            }
            if (statusResult != null && statusResult.isSuccess()) { item.setStatus(statusResult.getResult()); }
        }).collect(Collectors.toList()));
        return shopPrinterIPage;
    }

    @Override
    public String addShopPrinter(ShopPrinter shopPrinter) {
        if (super.baseMapper.selectCount(new LambdaQueryWrapper<ShopPrinter>()
                .eq(ShopPrinter::getNumber, shopPrinter.getNumber())
                .eq(ShopPrinter::getType, shopPrinter.getType())) > 0)
            throw new CheckFailedException("已有打印机编号为「" + shopPrinter.getNumber() + "」的打印机");

        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        shopPrinter.setCreateTime(new Date());
        shopPrinter.setCreateBy(loginUser.getUsername());
        shopPrinter.setDelFlag(CommonConstant.DEL_FLAG_0);
        shopPrinter.setLockVersion(1);

        final String ADD_ERROR_MESSAGE = "新增打印机失败";
        String errorMessage;
        // 飞鹅
        if (shopPrinter.getType() == 1) {
            errorMessage = FePrinterUtil.addPrinter(shopPrinter);
            // 易联云
        } else if (shopPrinter.getType() == 2) {
            errorMessage = YlyPrinterUtil.addPrinter(shopPrinter);
            // 芯烨云
        } else if (shopPrinter.getType() == 3) {
            errorMessage = XyyPrinterUtil.addPrinter(shopPrinter);
            // 中午
        } else if (shopPrinter.getType() == 4) {
            errorMessage = null;
        } else {
            throw new JeecgBootException("暂不支持的打印机类型");
        }
        if (errorMessage != null) {
            throw new JeecgBootException(ADD_ERROR_MESSAGE + ", " + errorMessage);
        }
        super.baseMapper.insert(shopPrinter);
        if (shopPrinter.getId() == null) { throw new JeecgBootException(ADD_ERROR_MESSAGE); }

        return shopPrinter.getId();
    }

    @Override
    public int updateShopPrinter(ShopPrinter shopPrinter) {
        shopPrinter.setUpdateTime(new Date());
        shopPrinter.setUpdateBy(((LoginUser) SecurityUtils.getSubject().getPrincipal()).getUsername());
        shopPrinter.setDelFlag(null);

        final String EDIT_ERROR_MESSAGE = "更新打印机失败";
        ShopPrinter shopPrinterDB = super.baseMapper.selectById(shopPrinter.getId());
        // 根据传过来的id从数据库查出来的如果为空，直接抛出
        if (shopPrinterDB == null)
            throw new JeecgBootException(EDIT_ERROR_MESSAGE + ", id-> " + shopPrinter.getId());

        // 如果数据库的流量卡号和传过来的流量卡号不相等，那么才进行更新操作
        if (!StringUtils.equals(shopPrinter.getSimNumber(), shopPrinterDB.getSimNumber())) {
            String errorMessage;
            // 飞鹅
            if (shopPrinter.getType() == 1) {
                errorMessage = FePrinterUtil.updatePrinter(shopPrinter);
                // 易联云
            } else if (shopPrinter.getType() == 2) {
                errorMessage = YlyPrinterUtil.addPrinter(shopPrinter);
                // 芯烨云
            } else if (shopPrinter.getType() == 3) {
                errorMessage = XyyPrinterUtil.addPrinter(shopPrinter);
                // 中午
            } else if (shopPrinter.getType() == 4) {
                errorMessage = null;
            } else {
                throw new JeecgBootException("暂不支持的打印机类型");
            }
            if (errorMessage != null) {
                throw new JeecgBootException(EDIT_ERROR_MESSAGE + ", " + errorMessage);
            }
        }

        // 不管流量卡号相不相等，数据库还是要更新的
        int updateRecordCount = super.baseMapper.updateById(shopPrinter);
        if (updateRecordCount == 0)
            throw new JeecgBootException(EDIT_ERROR_MESSAGE + ", id-> " + shopPrinter.getId());
        return updateRecordCount;
    }

    @Override
    public int deleteShopPrinter(String id) {
        ShopPrinter shopPrinter = super.baseMapper.selectById(id);
        if (shopPrinter == null)
            throw new JeecgBootException("未找到相应的打印机信息, id-> " + id);

        final String DELETE_ERROR_MESSAGE = "删除打印机失败";
        int deleteRecordCount = super.baseMapper.deleteById(id);
        String errorMessage;
        // 飞鹅
        if (shopPrinter.getType() == 1) {
            errorMessage = FePrinterUtil.deletePrinter(shopPrinter.getNumber());
            // 易联云
        } else if (shopPrinter.getType() == 2) {
            errorMessage = YlyPrinterUtil.deletePrinter(shopPrinter.getNumber());
            // 芯烨云
        } else if (shopPrinter.getType() == 3) {
            errorMessage = XyyPrinterUtil.deletePrinter(shopPrinter.getNumber());
            // 中午
        } else if (shopPrinter.getType() == 4) {
            errorMessage = null;
        } else {
            throw new JeecgBootException("暂不支持的打印机类型");
        }
        if (errorMessage != null) {
            throw new JeecgBootException(DELETE_ERROR_MESSAGE + ", " + errorMessage);
        }
        if (deleteRecordCount == 0) {
            throw new JeecgBootException(DELETE_ERROR_MESSAGE + ", id-> " + id);
        }
        return deleteRecordCount;
    }

    @Override
    public void deleteBatchShopPrinter(List<String> ids) {
        ids.forEach(this::deleteShopPrinter);
    }

    @Override
    public List<ShopPrinter> getShopPrinterByShopId(String shopId) {
        return super.baseMapper.selectList(new LambdaQueryWrapper<ShopPrinter>().eq(ShopPrinter::getShopId, shopId));
    }

}
